const Service = require('egg').Service;

class MenuService extends Service {

	async list () {
		const res = await this.app.mysql.get('sys').query(
			' select id, pid, name, href, icon, isshow, sort from dlq_menu ' + 
			' where del_flag = "0" ' + 
			' order by sort '
		);

		return res;
	}


	async create (pid, name, href, icon, sort, isshow) {
		const res = await this.app.mysql.get('sys').query(
			' insert into dlq_menu ' + 
			' (id, pid, name, href, icon, sort, isshow, create_time, update_time) ' + 
			' values ' + 
			' (uuid(), ?, ?, ?, ?, ?, ?, now(), now()) ', [pid, name, href, icon, sort, isshow]
		);

		console.log(res);

		return res.affectedRows === 1;
	}

	async update (name, href, icon, sort, isshow, id) {
		const res = await this.app.mysql.get('sys').query(
			' update dlq_menu set ' + 
			' name = ?, href = ?, icon = ?, sort = ?, isshow = ? , update_time = now() ' + 
			' where ' + 
			' id = ? ', [name, href, icon, sort, isshow, id]
		);

		console.log(res);

		return res.affectedRows === 1;
	}


	async delete (id) {
		const res = await this.app.mysql.get('sys').query(
			' update dlq_menu set ' + 
			' del_flag = "1", update_time = now() ' + 
			' where ' + 
			' id = ? ', [id]
		);

		console.log(res);

		return res.affectedRows === 1;
	}

	async getUserMenu (roleIds) {
		const res = await this.app.mysql.get('sys').query(
			' select distinct m.id, pid, name, href, icon, isshow, sort , rm.checked as state ' + 
			' from dlq_menu as m  ' + 
			' left join dlq_role_menu as rm on m.id = rm.menu_id ' +
			' where m.del_flag = "0" and rm.role_id in (1) and m.isshow = "1" ' +
			' order by m.sort' , [roleIds]
		);

		console.log(roleIds);
		console.log(res);

		return res;
	}

	async getMenuByRole (roleId) {
		const res = await this.app.mysql.get('sys').query(
			' select  m.id, pid, name, href, icon, isshow, sort , rm.checked as state ' + 
			' from dlq_menu as m  ' + 
			' left join dlq_role_menu as rm on m.id = rm.menu_id and rm.role_id=? ' +
			' where m.del_flag = "0" ' +
			' order by m.sort' , [roleId]
		);

		return res;
	}
}

module.exports = MenuService;